package com.zero.controller;

import com.zero.entity.Email;
import com.zero.entity.FamilyMember;
import com.zero.service.EmailService;
import com.zero.util.Constant;
import com.zero.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/adminEmail")
    public Result getAllEmail(@RequestBody Email email){

        //设置邮件类型为管理员类型
        return emailService.getEmail(email);
    }

    @PostMapping("/feedbackImg")
    public Result upload(MultipartFile file) throws FileNotFoundException {
        if (file.isEmpty()) {
            return Result.fail("文件为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径

        // 解决中文问题，liunx下中文路径，图片显示问题
        fileName = UUID.randomUUID() + suffixName;
        //File.separator获取不同操作系统下的分隔符。
        File dest = new File(Constant.FEEDBACK_FILE_PATH + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
//            System.out.println(dest.getAbsolutePath().replaceAll("\\\\", "/"));
            return Result.ok("上传成功", dest.getAbsolutePath().replaceAll("\\\\", "/"));
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail("上传失败");
    }

    @GetMapping("/feedbackImg")
    public ResponseEntity<byte[]> getImg(@RequestParam("img") String img, HttpServletRequest request, HttpServletResponse response) {
        File file = new File(img);
        if (!file.exists())
            return null;
        //通过自己写的http工具类获取到图片输入流
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //将输入流转为byte[]
        byte[] bytesByStream = getBytesByStream(inputStream);
        final HttpHeaders headers = new HttpHeaders();
        String ext = img.substring(img.lastIndexOf(".") + 1);
        //判断图片格式,设置相应的输出文件格式
        if(ext.equals("jpg")){
            headers.setContentType(MediaType.IMAGE_JPEG);
        }else if(ext.equals("JPG")){
            headers.setContentType(MediaType.IMAGE_JPEG);
        }else if(ext.equals("png")){
            headers.setContentType(MediaType.IMAGE_PNG);
        }else if(ext.equals("PNG")){
            headers.setContentType(MediaType.IMAGE_PNG);
        }
        return new ResponseEntity<>(bytesByStream, headers, HttpStatus.OK);
    }

    public byte[] getBytesByStream(InputStream inputStream){
        byte[] bytes = new byte[1024];

        int b;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            while((b = inputStream.read(bytes)) != -1){

                byteArrayOutputStream.write(bytes,0,b);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/feedbackEmail")
    public Result feedbackEmail(@RequestBody Email email, HttpServletRequest request){
        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到用户信息");

        email.setMemberId(familyMember.getId());
        return emailService.addEmail(email);
    }

    @GetMapping("/markEmail")
    public Result markEmail(@RequestParam("id") int id){
        return emailService.markEmail(id);
    }

    @GetMapping("/deleteEmail")
    public Result deleteEmail(@RequestParam("ids") String ids){
        return emailService.deleteEmail(ids);
    }
}
